import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { RouteRecordName } from 'vue-router'

export type Tags = {
  path: string
  name?: RouteRecordName | null
  meta?: {
    title: string
    icon?: string
    locale?: string
    breadcrumb?: boolean
    url?: string
    iframeUrl?: string
    iframeData?: any
  }
  remove?: boolean
  query?: {}
  params?: {}
}

export const useTagsStore = defineStore('tags', () => {
  const tags = ref<Tags[]>([
    {
      path: '/home',
      name: 'home_page',
      meta: {
        title: '首页',
      },
      remove: true,
    },
  ])

  type Tag = {
    to?: Tags
    removeIndex?: number[]
    name?: string
  }
  /**
   * 标签数据操作
   * @param {Tag} tag
   */
  const tagsOperate = (tag: Tag) => {
    if (tag.removeIndex !== undefined || tag.name !== undefined) {
      if (tag.name) {
        const names = [tag.name, tags.value[0].name]
        console.log(names)
        tags.value = tags.value.filter(
          item => names.indexOf(item.name as string) !== -1,
        )
        return
      }

      tag.removeIndex &&
        tags.value.splice(tag.removeIndex[0], tag.removeIndex[1])
    } else {
      try {
        tags.value.push(tag.to!)
      } catch (err) {
        console.error(err)
      }
    }
  }

  return {
    tags,
    tagsOperate,
  }
})
